/*
 * simple_config.cpp
 *
 *  Created on: Dec 27, 2014
 *      Author: liao
 */
#include <fstream>
#include <sstream>
#include "simple_config.h"
#include <stdio.h>

/*
去掉字符串首尾的 \x20 \r \n 字符
by sincoder
*/
void clean_string( char *str )
{
//      ASSERT( str != NULL );

      char *start = NULL;
      char *end = NULL;
      char *p = str;

      while ( ( *p != 0) && (*p == ' ' || *p == '\r' || *p == '\n' || *p == '\t') )

     {

         p++;

     }
     if ( *p == 0 )

     {

         *str = 0;

         return;

     }

     else

     {

         start = p;              // mark the first no-blank position
          while( *(p+1)  != 0 )   // move p to str end
  
         {
              p++;
          }
      }
      while ( *p == ' ' || *p == '\r' || *p == '\n' || *p == '\t' )

     {
          p--;
      }
      end = p;
      int newLen = (int)(end - start + 1);

     memmove( str, start, newLen );
  
     *(str + newLen ) = 0;

}


int get_config_map(const char *config_file, std::map<std::string, std::string> &configs) {
    std::ifstream fs(config_file);
    if(!fs.is_open()) {
        return -1;
    }

    while(fs.good()) {
        std::string line;
        std::getline(fs, line);

        if (line[0] == '#') {
            continue;
        }
        std::stringstream ss;
        ss << line;
        std::string key, value;
        std::getline(ss, key, '=');
        std::getline(ss, value, '=');
    	char stemp[256];
		memset(stemp, 0, sizeof(stemp));
		memcpy(stemp, value.c_str(), value.size());
		clean_string(stemp);
        configs[key] = stemp;
    }
    fs.close();
    return 0;
}